from flask import Flask, render_template, request, jsonify
import json
import requests
from datetime import datetime
import os
import sqlite3

app = Flask(__name__)

# 数据库初始化
def init_db():
    """初始化SQLite数据库，创建历史记录表"""
    conn = sqlite3.connect('history.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS history
        (id INTEGER PRIMARY KEY AUTOINCREMENT,
         api_url TEXT NOT NULL,
         ts_type TEXT NOT NULL,
         created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
    ''')
    conn.commit()
    conn.close()

def convert_to_ts_type(data, parent_key=''):
    """
    将JSON数据转换为TypeScript类型定义
    params:
        data: JSON数据
        parent_key: 父级键名，用于生成注释
    """
    if isinstance(data, dict):
        fields = []
        for key, value in data.items():
            ts_type = get_ts_type(value, key)
            comment = f"/** {key} - {get_description(value)} */"
            fields.append(f"    {comment}\n    {key}: {ts_type};")
        return "{\n" + "\n".join(fields) + "\n}"
    return get_ts_type(data)

def get_ts_type(value, key=''):
    """
    获取TypeScript类型
    """
    if isinstance(value, str):
        return "string"
    elif isinstance(value, bool):
        return "boolean"
    elif isinstance(value, int):
        return "number"
    elif isinstance(value, float):
        return "number"
    elif isinstance(value, list):
        if len(value) > 0:
            return f"{get_ts_type(value[0])}[]"
        return "any[]"
    elif isinstance(value, dict):
        return convert_to_ts_type(value, key)
    elif value is None:
        return "null"
    return "any"

def get_description(value):
    """
    生成字段描述
    """
    if isinstance(value, dict):
        return "对象"
    elif isinstance(value, list):
        return "数组"
    elif isinstance(value, str):
        return "字符串"
    elif isinstance(value, bool):
        return "布尔值"
    elif isinstance(value, int):
        return "整数"
    elif isinstance(value, float):
        return "浮点数"
    elif value is None:
        return "空值"
    return "未知类型"

@app.route('/')
def index():
    """渲染主页"""
    return render_template('index.html')

@app.route('/convert', methods=['POST'])
def convert():
    """处理API转换请求"""
    try:
        if not request.is_json:
            return jsonify({'success': False, 'error': '请求必须是 JSON 格式'})
        api_url = request.json['api_url'] if request.json else None
        if not api_url:
            return jsonify({'success': False, 'error': 'API URL 不能为空'})
            
        response = requests.get(api_url)
        data = response.json()
        
        # 生成TypeScript类型定义
        ts_type = f"export interface ApiResponse {convert_to_ts_type(data)}"
        
        # 保存到历史记录
        conn = sqlite3.connect('history.db')
        c = conn.cursor()
        c.execute('INSERT INTO history (api_url, ts_type) VALUES (?, ?)',
                 (api_url, ts_type))
        conn.commit()
        conn.close()
        
        return jsonify({'success': True, 'ts_type': ts_type})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@app.route('/history')
def get_history():
    """获取历史记录"""
    conn = sqlite3.connect('history.db')
    c = conn.cursor()
    c.execute('SELECT * FROM history ORDER BY created_at DESC')
    history = [{'id': row[0], 'api_url': row[1], 'ts_type': row[2], 
                'created_at': row[3]} for row in c.fetchall()]
    conn.close()
    return jsonify(history)

@app.route('/clear-history', methods=['POST'])
def clear_history():
    """清空历史记录"""
    conn = sqlite3.connect('history.db')
    c = conn.cursor()
    c.execute('DELETE FROM history')
    conn.commit()
    conn.close()
    return jsonify({'success': True})

if __name__ == '__main__':
    # 确保数据库表已创建
    init_db()
    # 启动Flask应用
    app.run(host='0.0.0.0', port=5000)  # 移除 debug=True